package com.ellecity06.cwhiskymall.ui.user

import android.app.Activity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.loadByUser
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.upPath
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.imageSelect
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.bean.response.MemberInfo
import com.ellecity06.cwhiskymall.databinding.ActivityUserInfoBinding
import com.ellecity06.cwhiskymall.ui.mine.MineIntent
import com.ellecity06.cwhiskymall.ui.mine.MineState


/**
 * @author ellecity06
 * @time 2024/10/26 11:53
 * @des 个人中心页面
 */
class UserInfoActivity : BaseMvvmActivity<ActivityUserInfoBinding, UserInfoViewModel>(),
    View.OnClickListener {
    override fun inflateBinding(): ActivityUserInfoBinding {
        return ActivityUserInfoBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        title = "个人信息"
        setRightText("保存")
        initView()
        fetchUser()


    }

    override fun onBackPressed() {
//        super.onBackPressed()
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(UserInfoIntent.Back(binding.tvName.text.toString()))
        }

    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is UserInfoState.UserInfo -> {
                    setUserInfo(it.user)
                }
                is UserInfoState.UpdateSuccess -> {
                    setResult(Activity.RESULT_OK)
                    finish()
                    ToastUtils.show("保存成功")
                }
                is UserInfoState.Back -> {
                    finish()
                }
                is UserInfoState.ShowConfirm -> {
                    showAlert(title = "您有数据尚未保存，确认退出？") {
                        finish()
                    }
                }
                is UserInfoState.DestroySuccess -> {
                    showAlert(title = "注销成功", "您的账户已经注销成功", showCancel = false) {
                        LoginHelper.instance.logout(this)
                    }
                }
                is UserInfoState.LogoutSuccess -> {
                    LoginHelper.instance.logout(this)
                }
                else -> {}
            }
        }
    }

    private fun setUserInfo(user: MemberInfo) {
        binding.ivAvatar.loadByUser(this, user.avatar)
        binding.tvName.setText(user.nickName ?: "暂无昵称")
        binding.tvPhone.text = user.phone
        binding.tvInviter.text = if (user.upShardCode.isNullOrEmpty()) "暂无邀请人" else user.upShardCode
        binding.tvRegisterTime.text = user.createTime
    }

    private fun fetchUser() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(UserInfoIntent.User)
        }
    }

    private fun destroyAccount() {
        showAlert(title = "注销账户", content = "您确定要注销账户吗？") {
            lifecycleScope.launchWhenCreated {
                viewModel.intentChannel.send(UserInfoIntent.DestroyAccount)
            }
        }

    }

    private fun initView() {
        setRightClickListener(this)
        binding.tvChange.setOnClickListener(this)
        binding.tvDestroyAccount.setOnClickListener(this)
        binding.ivAvatar.setOnClickListener(this)
        binding.tvLogoutAccout.setOnClickListener(this)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tv_title_right -> {
                saveUserInfo()
            }
            R.id.tv_change -> {

            }
            binding.ivAvatar.id -> {
                chooseImage()
            }
            R.id.tv_destroy_account -> {
                // 退出登录
                showAlert(title = "退出登录？",content = "确定退出登录吗？", onConfirm = {
                    logout()
                })
            }
            binding.tvLogoutAccout.id ->{
                destroyAccount()
            }
        }
    }
    private fun logout() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(UserInfoIntent.Logout)
        }
    }
    private fun saveUserInfo() {

        lifecycleScope.launchWhenCreated {
            val name = binding.tvName.text.toString().trim()
            viewModel.intentChannel.send(UserInfoIntent.EditUser(name))
        }
    }

    private fun chooseImage() {
        imageSelect(crop = true) {
            if (it != null && it.isNotEmpty()) {
                val localMedia = it[0]
                if (localMedia != null) {
                    val path = localMedia.upPath()
                    lifecycleScope.launchWhenCreated {
                        viewModel.intentChannel.send(UserInfoIntent.ImageSelect(path))
                    }
                    binding.ivAvatar.load(this, path)
                }

            }
        }

    }


    companion object {
        private const val REQUEST_LIST_CODE = 123
    }
}